package cn.cc.flex
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	import mx.core.IMXMLObject;
	import mx.events.ValidationResultEvent;
	import mx.validators.Validator;
	
	public class ValidatorManager extends EventDispatcher implements IMXMLObject
	{
		[Bindable]
		private var _validators:ArrayCollection;
		[Bindable]
		public var valid:Boolean= false;
		
		private var _validatorDic:Dictionary;
		public function initialized(document:Object, id:String):void{
			
		}
		
		public function set validators(validators:ArrayCollection):void{
			if(validators==null){
				this.valid = true;
				return;
			}
			this.valid = false;
			_validatorDic = new Dictionary();
			for each(var validator:Validator in validators){
				validator.addEventListener(ValidationResultEvent.INVALID,onInvalid);
				validator.addEventListener(ValidationResultEvent.VALID,onValid);
				_validatorDic[validator] = false;
			}
		}
		
		public function get validators():ArrayCollection{
			return this._validators;
		}
		
		
		private function onInvalid(e:ValidationResultEvent):void{
			this.dispatchEvent(e);
			_validatorDic[e.target] = false;
			valid = false;
		}
		private function onValid(e:ValidationResultEvent):void{
			_validatorDic[e.target] = true;
			for each(var item:Object in _validatorDic){
				if(!item){
					return;
				}
			}
			this.dispatchEvent(e);
			valid = true;
			//if (_validatorDic.hasOwnProperty(false);
		}
		
//		public function validateAll():void
//	    {   
//	    	var result:ValidationResultEvent;
//	        if (validators == null){
//	        	result = new ValidationResultEvent(ValidationResultEvent.VALID);
//	        } 
//	        
//	    	for each(var v:Validator in validators){
//	    		result = v.validate();
//	    		if (result.type == ValidationResultEvent.INVALID) {
//	    			errorMsg.push(result.message);
//	    		}
//	    	}
//	        if (errorMsg.length>0){
//	        	result = new ValidationResultEvent(ValidationResultEvent.INVALID);
//	        }else{
//	        	result = new ValidationResultEvent(ValidationResultEvent.VALID);
//	        }
//	        
//	        this.dispatchEvent(result);
//	       
//	    }

    
   
	}
	
}